package com.jackchong.base;

import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import android.view.OrientationEventListener;

import static android.view.OrientationEventListener.ORIENTATION_UNKNOWN;


/**
 * author : jack(黄冲)
 * e-mail : 907755845@qq.com
 * create : 2019/4/21
 * desc   : 重力感应监听
 */
public class OrientationListener implements SensorEventListener {

    private OrientationEnum mOrientation = OrientationEnum.PORTRAIT;
    private OnOrientationChangeListener mListener;
    private static final int _DATA_X = 0;
    private static final int _DATA_Y = 1;
    private static final int _DATA_Z = 2;

    public OrientationListener(OnOrientationChangeListener listener) {
        mListener = listener;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        float[] values = event.values;
        int orientation = ORIENTATION_UNKNOWN;
        float X = -values[_DATA_X];
        float Y = -values[_DATA_Y];
        float Z = -values[_DATA_Z];
        float magnitude = X * X + Y * Y;
        // Don't trust the angle if the magnitude is small compared to the y value
        if (magnitude * 4 >= Z * Z) {
            float OneEightyOverPi = 57.29577957855f;
            float angle = (float) Math.atan2(-Y, X) * OneEightyOverPi;
            orientation = 90 - (int) Math.round(angle);
            // normalize to 0 - 359 range
            while (orientation >= 360) {
                orientation -= 360;
            }
            while (orientation < 0) {
                orientation += 360;
            }
        }

        OrientationEnum anEnum = null;
        if (orientation > 45 && orientation < 135) {
            anEnum = OrientationEnum.REVERSE_LANDSCAPE;
        } else if (orientation > 135 && orientation < 225) {
            anEnum = OrientationEnum.REVERSE_PORTRAIT;
        } else if (orientation > 225 && orientation < 315) {
            anEnum = OrientationEnum.LANDSCAPE;
        } else if ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45)) {
            anEnum = OrientationEnum.PORTRAIT;
        }

        if (mListener != null && anEnum != null){
            mListener.orientationChanged(anEnum);
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public interface OnOrientationChangeListener {
        void orientationChanged(OrientationEnum newOrientation);
    }
}
